<?php


class DSUserIdentity extends CUserIdentity
{
    public function __construct($userName=false,$password=false)
    {
        if($userName) $this->username=$userName;
        if($password) $this->password=$password;
    }

    public function rules()
    {
        return array(
            array('username', 'required', 'message'=>'Укажите свой логин или электронный аадрес'),
            array('password', 'required', 'message'=>''),
        );
    }

    public function authenticate()
    {
        $model=$this->getUserModel();

        if($model===null || $model->password!==$model->getPasswordHash($this->password)){
            $this->errorCode='Не найдено такого соответсвия логина (e-mail адреса) и пароля.';
        }else{
            $this->login($model);
        }

        return !$this->errorCode;
    }

    public function getUserModel($userName='')
    {
        if(!$userName) $userName=$this->username;
        $model=strpos($userName,'@') ? User::model()->findByAttributes(array('email'=>$userName)) : User::model()->findByAttributes(array('userName'=>$userName));
        return $model;
    }

    public function login($userModel=false)
    {
        $this->_id=$userModel->id;
        $this->setState('name', $userModel->profile->firstName);
        if(Yii::app()->user->login($this)){
            $time=time();
            $userModel->lastLoginTime=$time;
            $userModel->statistics->dateVisit=$time;
            $userModel->statistics->update();
            $userModel->update();
            $this->errorCode=self::ERROR_NONE;
            return true;
        }
        return false;
    }

    public function logout($userModel=false)
    {
        if($userModel){
            $userModel->lastLoginTime=0;
            $userModel->update();
        }
        return Yii::app()->user->logout();
    }
}